package com.jxinternet.platform.services.handler;

import com.jxinternet.platform.services.coder.SocketModelDecoder;
import com.jxinternet.platform.services.entity.protobuf.SocketModelProtos;
import com.jxinternet.platform.services.entity.protobuf.SocketModelProtos.SocketModelResponse;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * netty业务处理
 */
@Slf4j
@Component
@Qualifier("protoBufServerHandler")
@ChannelHandler.Sharable
public class ProtoBufServerHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private SocketModelDecoder socketModelDecoder;


    /**
     * 客户端连接
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        System.out.println("Client:" + incoming.remoteAddress() + "加入");
        //log.info("Client:" + incoming.remoteAddress() + "加入");
    }

    /**
     * 客户端断开
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // NOOP
        Channel incoming = ctx.channel();
        System.out.println("Client:" + incoming.remoteAddress() + "离开");
        //log.info("Client:" + incoming.remoteAddress() + "离开");
    }

    /**
     * 客户端解码后请求
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        socketModelDecoder.step1_validateSocketModel(ctx, msg);

        SocketModelResponse socketModelResponse = socketModelDecoder.step2_Dispatch(ctx, msg);

        resp(ctx, socketModelResponse);

    }

    private void resp(ChannelHandlerContext ctx, SocketModelProtos.SocketModelResponse socketModelResponse) {

        ctx.writeAndFlush(socketModelResponse);

    }


}



